<template>
  <q-page class="q-pa-md">
    <!-- 查询表单 -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section>
        <div class="text-h6">登录日志查询</div>
      </q-card-section>
      <q-card-section>
        <q-form @submit="handleSearch" class="row q-col-gutter-md">
          <q-input
            v-model="searchForm.userName"
            label="用户账号"
            outlined
            dense
            clearable
            class="col-md-3 col-sm-6 col-xs-12"
          />
          <q-input
            v-model="searchForm.ipaddr"
            label="登录地址"
            outlined
            dense
            clearable
            class="col-md-3 col-sm-6 col-xs-12"
          />
          <q-select
            v-model="searchForm.status"
            label="登录状态"
            :options="statusOptions"
            outlined
            dense
            emit-value
            map-options
            class="col-md-3 col-sm-6 col-xs-12"
          />
          <div class="col-md-3 col-sm-6 col-xs-12">
            <q-input v-model="searchForm.dateRange" label="登录时间" outlined dense clearable>
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                    <q-date v-model="searchForm.dateRange" range />
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>
          <div class="col-md-12 flex justify-end">
            <q-btn type="submit" color="primary" label="查询" class="q-mr-sm" />
            <q-btn @click="resetSearch" label="重置" outline color="primary" />
            <q-btn color="grey" label="导出" icon="download" @click="exportData" class="q-ml-sm" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>

    <!-- 日志表格 -->
    <q-card flat bordered>
      <q-table
        :rows="loginLogs"
        :columns="columns"
        row-key="infoId"
        :loading="loading"
        :pagination="pagination"
        @request="onRequest"
        binary-state-sort
        flat
        bordered
      >
        <!-- 登录状态列 -->
        <template v-slot:body-cell-status="props">
          <q-td :props="props">
            <q-badge :color="props.row.status === '0' ? 'positive' : 'negative'">
              {{ props.row.status === '0' ? '成功' : '失败' }}
            </q-badge>
          </q-td>
        </template>

        <!-- 操作列 -->
        <template v-slot:body-cell-actions="props">
          <q-td :props="props" class="q-gutter-x-sm">
            <q-btn dense color="primary" icon="visibility" @click="showDetailDialog(props.row)">
              <q-tooltip>查看详情</q-tooltip>
            </q-btn>
            <q-btn dense color="negative" icon="delete" @click="confirmDelete(props.row.infoId)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </q-card>

    <!-- 日志详情对话框 -->
    <q-dialog v-model="detailDialog" persistent>
      <q-card style="min-width: 700px; max-width: 800px">
        <q-card-section>
          <div class="text-h6">登录日志详情</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <div class="row q-col-gutter-md q-mb-md">
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.userName" label="用户账号" outlined readonly />
            </div>
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.ipaddr" label="登录IP" outlined readonly />
            </div>
          </div>

          <div class="row q-col-gutter-md q-mb-md">
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.loginLocation" label="登录地点" outlined readonly />
            </div>
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.browser" label="浏览器" outlined readonly />
            </div>
          </div>

          <div class="row q-col-gutter-md q-mb-md">
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.os" label="操作系统" outlined readonly />
            </div>
            <div class="col-md-6 col-sm-12">
              <q-input
                :model-value="currentLog.status === '0' ? '成功' : '失败'"
                label="登录状态"
                outlined
                readonly
              />
            </div>
          </div>

          <div class="row q-col-gutter-md q-mb-md">
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.loginTime" label="登录时间" outlined readonly />
            </div>
            <div class="col-md-6 col-sm-12">
              <q-input v-model="currentLog.msg" label="操作信息" outlined readonly />
            </div>
          </div>

          <q-input
            v-model="currentLog.userAgent"
            label="User Agent"
            type="textarea"
            outlined
            readonly
            autogrow
            class="q-mb-md"
          />

          <q-input
            v-model="currentLog.errorMsg"
            label="错误消息"
            type="textarea"
            outlined
            readonly
            autogrow
            v-if="currentLog.status !== '0'"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn label="关闭" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'infoId', label: '日志ID', field: 'infoId', align: 'center', sortable: true },
  { name: 'userName', label: '用户账号', field: 'userName', align: 'center' },
  { name: 'ipaddr', label: '登录IP', field: 'ipaddr', align: 'center' },
  { name: 'loginLocation', label: '登录地点', field: 'loginLocation', align: 'center' },
  { name: 'browser', label: '浏览器', field: 'browser', align: 'center' },
  { name: 'os', label: '操作系统', field: 'os', align: 'center' },
  { name: 'status', label: '登录状态', field: 'status', align: 'center' },
  { name: 'loginTime', label: '登录时间', field: 'loginTime', align: 'center', sortable: true },
  { name: 'actions', label: '操作', align: 'center' },
]

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '成功', value: '0' },
  { label: '失败', value: '1' },
]

// 数据状态
const loginLogs = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const searchForm = ref({
  userName: '',
  ipaddr: '',
  status: '',
  dateRange: { from: '', to: '' },
})

// 日志详情相关
const detailDialog = ref(false)
const currentLog = ref({
  infoId: '',
  userName: '',
  ipaddr: '',
  loginLocation: '',
  browser: '',
  os: '',
  status: '',
  msg: '',
  loginTime: '',
  userAgent: '',
  errorMsg: '',
})

// 初始化加载数据
onMounted(() => {
  loadLoginLogs()
})

// 加载登录日志
function loadLoginLogs(props) {
  if (!props) {
    props = { pagination: pagination.value }
  }

  loading.value = true
  const { page, rowsPerPage } = props.pagination

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    const mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
      infoId: (page - 1) * rowsPerPage + i + 1,
      userName: ['admin', 'test', 'user1', 'dev', 'manager'][i % 5],
      ipaddr: ['192.168.1.' + (i + 1), '10.0.0.' + (i + 1), '172.16.0.' + (i + 1)][i % 3],
      loginLocation: ['内网IP', '北京市', '上海市', '广州市', '深圳市'][i % 5],
      browser: ['Chrome', 'Firefox', 'Edge', 'Safari', 'Opera'][i % 5],
      os: ['Windows 10', 'Mac OS X', 'Linux', 'Windows 11', 'iOS'][i % 5],
      status: i % 10 === 0 ? '1' : '0', // 10%的概率模拟失败
      msg: ['登录成功', '密码错误', '验证码错误', '账户已锁定', '账户已过期'][i % 5],
      loginTime: new Date(Date.now() - i * 3600 * 1000).toISOString(),
      userAgent: [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59',
      ][i % 5],
      errorMsg: i % 10 === 0 ? 'Bad credentials: 密码错误' : '',
    }))

    // 应用查询条件
    let filteredData = [...mockData]
    if (props.filter.userName) {
      filteredData = filteredData.filter((item) => item.userName.includes(props.filter.userName))
    }
    if (props.filter.ipaddr) {
      filteredData = filteredData.filter((item) => item.ipaddr.includes(props.filter.ipaddr))
    }
    if (props.filter.status) {
      filteredData = filteredData.filter((item) => item.status === props.filter.status)
    }
    if (props.filter.dateRange.from && props.filter.dateRange.to) {
      const fromDate = new Date(props.filter.dateRange.from)
      const toDate = new Date(props.filter.dateRange.to)
      filteredData = filteredData.filter((item) => {
        const itemDate = new Date(item.loginTime)
        return itemDate >= fromDate && itemDate <= toDate
      })
    }

    loginLogs.value = filteredData
    pagination.value.rowsNumber = filteredData.length
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
    loading.value = false
  }, 500)
}

// 表格请求方法
function onRequest(props) {
  loadLoginLogs(props)
}

// 查询处理
function handleSearch() {
  pagination.value.page = 1
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 重置查询
function resetSearch() {
  searchForm.value = {
    userName: '',
    ipaddr: '',
    status: '',
    dateRange: { from: '', to: '' },
  }
  handleSearch()
}

// 显示详情对话框
function showDetailDialog(row) {
  currentLog.value = { ...row }
  detailDialog.value = true
}

// 确认删除
function confirmDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该登录日志吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '登录日志已删除',
    })
    loadLoginLogs()
  })
}

// 导出数据
function exportData() {
  $q.notify({
    type: 'positive',
    message: '导出成功',
  })
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }
}

// 固定详情对话框的宽度
.q-dialog__inner--minimized > div {
  max-width: 800px;
}
</style>
